export const key = "shopdata"; //让loaclStorage存储的数据都以这个作为标识
export var valueObj ={goodId:0,count:0}
export function setItem(value){
    var str = localStorage.getItem(key) || "[]";
    var strArr = JSON.parse(str);
    strArr.push(value);
    localStorage.setItem(key,JSON.stringify(strArr));
};
export function getItem(){
    var str=localStorage.getItem(key) || "[]";
    var strObj=JSON.parse(str);
    return strObj;
}
//getgoodsObj这个函数操作是将前面放进本地存储localStorage里的 数组遍历后变成
//{goodId89:4,goodId90:5}
export function getgoodsObj(){
    var arr=getItem();
    var resObj={};
    for(var i=0; i<arr.length; i++){
        var item = arr[i];
        if(!resObj[item.goodId]){
            resObj[item.goodId] = item.count; //这一步相当于给resObj属性id号赋值数量
        }else{
             resObj[item.goodId]+=item.count;
        }
    }
    return resObj;
}
//点击加减组件后需要更新localStorage里的数据的方法
export function updataObj(obj){
    var arr = getItem();
    var count=1;
    if(obj.type=="add"){
        arr.push({goodId:obj.goodId,count:count});
    }else{
        for(var i=0; i<arr.length; i++){
            if(obj.goodId==arr[i].goodId){
                if (arr[i].count > 1) {
                    arr[i].count--;
                    break;
                } else {
                    arr.splice(i, 1);
                    break;
                }
            }
            
        }
    }
    localStorage.setItem(key, JSON.stringify(arr));
}